/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package battle.ship.controller;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author Carlos
 */
public class Client extends JFrame{
    
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String chatServer;
    private Socket client;
 
    //inicializar Cliente e  criar GUI
 public Client(String host)
 {
     super("Client");
     
     chatServer = host;
     
     enterField = new JTextField();
     enterField.setEditable(false);
     enterField.addActionListener(
             new ActionListener(){
                 //enviar mensagem para servidor
                 public void actionPerformed(ActionEvent evt)
                 {
                     sendData(evt.getActionCommand());
                     enterField.setText("");
                 }
             }
             );
     add(enterField, BorderLayout.NORTH);
     
     displayArea = new JTextArea();
     add(new JScrollPane(displayArea), BorderLayout.CENTER);
     
     setSize(300, 150);
     setVisible(true);
 }
 //Ligar ao servidor e procesar mensagem de retorno
 public void runClient(Inet4Address iNA)
 {
    
    
    try //ligaçao ao server
    {
       connectToServer();
       getStreams();
       ProcessConnection();
       }
        catch(EOFException eofE)
        {
        displayMessage("Client terminated Connection");
        }catch(IOException ioE){
        ioE.printStackTrace();
        }
        finally{
          closeConnection();
    }
}
 //ligar ao servidor
 private void connectToServer() throws IOException
 {
     displayMessage("Tentar ligação");
     
    //criar socket para fazer ligaçao ao servidor(hostname, porta)
     client = new Socket(InetAddress.getByName(chatServer),12345);
     
     displayMessage("Ligado a"+client.getInetAddress().getHostName());
 }
 // pegar streams de objectos para enviar e receber
 private void getStreams() throws IOException
 {
     output = new ObjectOutputStream(client.getOutputStream());
     output.flush();
     
     input = new ObjectInputStream(client.getInputStream());
     
     displayMessage("Transferindo Streams");
 }
 //processar ligaçao com servidor
 private void ProcessConnection() throws IOException{
     setTextFieldEditable(true);
     do{
        try{
            message = (String) input.readObject();
            displayMessage("\n"+message);
        } catch(ClassNotFoundException cNFE){
            displayMessage("\n tipo Objecto desconhecido!");
        }
     }while (!message.equals("SERVER>>> TERMINATE"));
 }
 //metodo para fechar ligaçao
 private void closeConnection(){
     displayMessage("\n fechado Ligaçao");
     setTextFieldEditable(false);
     
     try{
         output.close();
         input.close();
         client.close();
     }
     catch(IOException iOE){
         iOE.printStackTrace();
     }
 }
 //enviar mensagem ao servidor
 private void sendData(String message){
     try{
         output.writeObject("CLIENT>>> "+ message);
         output.flush();
         displayMessage("\nClIENT>>>"+ message);
     }catch(IOException iOE){
         displayArea.append("\n ERRO escrever objecto");
     }
 }
 //manpular display area no dispachador de eventos
 private void displayMessage(final String messageToDisplay)
 {
     SwingUtilities.invokeLater(
             new Runnable(){
                 public void run(){
                     displayArea.append(messageToDisplay);
                 }
             }
             );
 }
 private void setTextFieldEditable(final boolean editable)
 {
     SwingUtilities.invokeLater(
             new Runnable(){
                 public void run()
                 {
                     enterField.setEditable(editable);
                 }
             }
             );
 }
}

